<template>
  <div class="order">
    <div class="plus"></div>
    <van-nav-bar
      title="我的订单"
      left-text="返回"
      left-arrow
      @click-left="goBack"
      placeholder
    />
    <div class="bg"></div>
    <div class="content">
      <div class="box">
        <div class="orderNav">
          <van-tabs
            v-model="active"
            title-active-color="#ff594d"
            sticky
            offset-top="46px"
            @change="changeOrderStatus"
          >
            <van-tab
              :title="item.title"
              v-for="(item, index) in tabList"
              :key="index"
            >
              <div v-if="orderList.length > 0">
                <div
                  class="order-info"
                  v-for="(item, index) in orderList"
                  :key="index"
                >
                  <div class="title">
                    <div class="oid">{{ item.oid }}</div>
                    <div
                      class="status confirm"
                      v-if="item.status == 1"
                      @click="confirm(item, index)"
                    >
                      确认收货
                    </div>
                    <div class="status-box" v-else>
                      <div class="status">已完成</div>
                      <van-icon
                        class="del"
                        name="delete-o"
                        size="16px"
                        @click="delOrder(item, index)"
                      />
                    </div>
                  </div>
                  <div class="product">
                    <ProList v-for="(v, i) in item.data" :key="i" :proData="v">
                      <div class="count" slot="count">x{{ v.count }}</div>
                    </ProList>
                  </div>
                  <div class="total">
                    <div class="time">
                      {{ item.date | formatDate("yyyy-MM-dd hh:mm:ss") }}
                    </div>
                    <div class="bottom">
                      <div class="number">
                        共计<span>{{ item.number }}</span
                        >件
                      </div>
                      <div class="price">
                        合计<span>&yen;</span>{{ item.total }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else>
                <van-empty description="没有订单数据了" />
              </div>
            </van-tab>
          </van-tabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ProList from "@/components/ProList.vue";

export default {
  name: "Order",

  components: {
    ProList,
  },

  data() {
    return {
      active: 0,
      tabList: [{ title: "全部" }, { title: "进行中" }, { title: "已完成" }],
      orderList: [],
    };
  },

  created() {
    // 获取订单（初始化获取所有订单）
    this.getOrder(this.active);
  },

  computed: {
    // 计算订单中商品总数量
    number() {
      let count = 0;
      this.orderList.forEach((v) => {
        count += v.count;
      });
      return count;
    },
    // 计算订单中商品总价格
    price() {
      let count = 0;
      this.orderList.forEach((v) => {
        count += v.count * v.price;
      });
      return count;
    },
  },

  methods: {
    goBack() {
      this.$router.replace({ name: "User" });
    },

    // 获取订单
    getOrder(status) {
      // status订单状态
      // 其中 status 值为 0, 1, 2 ==> 0: 全部，1: 进行中，2: 已完成
      let tokenString = this.$cookies.get("TOKEN");
      this.axios
        .get("findOrder", {
          params: {
            tokenString,
            status,
          },
        })
        .then((res) => {
          //
          if (res.data.code == 700) {
            this.$toast("请先登录");
            // 清除token
            this.$cookies.remove("TOKEN");
            // 延迟2秒后跳转到登录页面
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.$router.replace({ name: "Login" });
            }, 2000);
            return;
          }
          if (res.data.code === 70000) {
            let data = res.data.result;
            // 获取订单编号
            // 定义保存oid的数组
            let oids = [];
            // 遍历后台返回的散装数据
            data.forEach((v) => {
              // 处理图片格式
              v.small_img = v.smallImg;
              // 去重找出唯一的oid
              if (oids.indexOf(v.oid) == -1) {
                oids.push(v.oid);
              }
            });
            // 按照订单编号分类数据
            // 定义一个保存处理后的数据的数组
            let array = [];
            // 循环遍历oid数组
            oids.forEach((ov) => {
              // 定义保存每个订单数据格式的对象
              let obj = {
                // 订单编号
                oid: ov,
                // 时间
                date: "",
                // 订单内商品数量
                number: 0,
                // 订单内商品总价
                total: 0,
                // 订单状态
                status: "",
                // 商品数据
                data: [],
              };
              // 遍历后台返回的数据
              data.forEach((dv) => {
                // 如果与当前oid匹配
                //
                if (dv.oid === ov) {
                  obj.date = dv.createdAt;
                  obj.number += dv.count;
                  obj.total += dv.count * dv.price;
                  obj.status = dv.status;
                  obj.data.push(dv);
                }
              });
              array.push(obj);
            });
            this.orderList = array;
          }
        })
        .catch((err) => {});
    },

    // 切换查询不同状态订单
    changeOrderStatus() {
      this.getOrder(this.active);
    },

    // 确认收货
    confirm(item, index) {
      this.$dialog
        .confirm({
          title: "提示",
          message: "是否确认收货？",
        })
        .then(() => {
          let tokenString = this.$cookies.get("TOKEN");
          this.axios
            .post("receive", {
              tokenString,
              oid: item.oid,
            })
            .then((res) => {
              //
              if (res.data.code == 700) {
                this.$toast("请先登录");
                // 清除token
                this.$cookies.remove("TOKEN");
                // 延迟2秒后跳转到登录页面
                let timer = setTimeout(() => {
                  clearTimeout(timer);
                  this.$router.replace({ name: "Login" });
                }, 2000);
                return;
              }
              if (res.data.code === 80000) {
                this.$toast(res.data.msg);
                // 将该商品数据的状态改为已完成
                item.status = 2;
                // 如果是在进行中确认收货则要删除该条商品数据
                if (this.active === 1) {
                  this.orderList.splice(index, 1);
                }
              }
            })
            .catch((err) => {});
        })
        .catch(() => {});
    },

    // 删除订单
    delOrder(item, index) {
      this.$dialog
        .confirm({
          title: "提示",
          message: "是否确认删除订单？",
        })
        .then(() => {
          let tokenString = this.$cookies.get("TOKEN");
          this.axios
            .post("removeOrder", {
              tokenString,
              oid: item.oid,
            })
            .then((res) => {
              //
              if (res.data.code == 700) {
                this.$toast("请先登录");
                // 清除token
                this.$cookies.remove("TOKEN");
                // 延迟2秒后跳转到登录页面
                let timer = setTimeout(() => {
                  clearTimeout(timer);
                  this.$router.replace({ name: "Login" });
                }, 2000);
                return;
              }
              if (res.data.code === 90000) {
                this.$toast(res.data.msg);
                // 删除订单后需要在orderList中删除订单数据
                this.orderList.splice(index, 1);
              }
            })
            .catch((err) => {});
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.van-icon {
  color: #ffa341;
}
/deep/.van-nav-bar__text {
  color: #ffa341;
}
/deep/.van-nav-bar__title {
  color: #333;
}
// /deep/.order .content .box .order-info .title .del

.order {
  .bg {
    width: 100%;
    height: 100px;
    background: #ff594d;
  }
  .content {
    margin-top: -30px;
    padding: 10px;
    color: #666;
    font-size: 14px;
    box-sizing: border-box;
    .box {
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      overflow: hidden;
      /deep/ .van-tabs__line {
        background-color: #ff594d;
      }
      .order-info {
        margin-top: 10px;
        padding: 12px;
        background: #fff;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        .title {
          display: flex;
          align-items: center;
          .oid {
            flex: 1;
          }
          .status {
            color: #999;
          }
          .status-box {
            display: flex;
            align-items: center;
          }
          .confirm {
            color: #ffa341;
          }
          .del {
            margin-top: 2px;
            margin-left: 10px;
            color: #999;
          }
        }
        .product {
          padding-bottom: 15px;
          .count {
            color: #999;
          }
        }
        .total {
          position: relative;
          padding-top: 15px;
          border-top: 1px dashed #d4d4d4;
          &::after,
          &::before {
            position: absolute;
            top: -9px;
            display: block;
            width: 18px;
            height: 18px;
            background: #f7f8fa;
            border-radius: 100%;
            content: "";
          }
          &::after {
            left: -20px;
          }
          &::before {
            right: -20px;
          }
          .time {
            margin: 5px 0;
          }
          .bottom {
            display: flex;
          }
          .price {
            margin-left: auto;
            color: #ff594d;
            font-size: 13px;
            font-weight: bold;
          }
          span {
            padding: 0 3px;
          }
        }
      }
    }
  }
}
</style>